//
//  MarksViewModel.swift
//  Automobile
//
//  Created by erkebulan elzhan on 9/3/20.
//  Copyright © 2020 erkebulan elzhan. All rights reserved.
//

import Foundation

final class MarksViewModel {
    
    var delegate: ViewModelProtocol!
    
    var selectedMode: MarkaModelMode = .include
    
    var selectedMarka: Marka!
    
    var data: [Marks] = []
    
    var filteredData: [Marks] = [] {
        didSet {
            self.delegate.updatePosts()
        }
    }
    
    var carData: CarData! = CarData()
    
    var resultDelegate: ResultsVCDelegate?
    
    var isCarCreate: Bool {
        return resultDelegate is SelectCarViewController
    }
    
    var nextURL: String?
    
    var searchTask: DispatchWorkItem?
    
    var lastSearchBarTxt: String?
    
    private let backendService = Backend()
}


// MARK: - Network

extension MarksViewModel {
    
    func loadMarks (pagination: Bool = false, query: String? = nil) {
        
        let request = self.makeRequest(pagination: pagination, query: query)
        
        self.delegate.updateSpinner(showSpinner: true)
        
        backendService.fetchFromBackend(for: Response<[Marka]>.self, request: request, statusCode: 200) { (result) in
            self.delegate.updateSpinner(showSpinner: false)
            switch result {
            case .failure(let err):
                self.delegate.didHappenError(error: err)
            case .success(let response):
                self.handleLoadedData(data: response, paginate: pagination)
                self.loadPopular()
            }
        }
    }
    
    func loadPopular () {
        let requestURL = Request(base: carData.saveToGarage ? .garage : .advert, limit: 4).getUrl(path: "cars/marks")
        let request = URLRequest(url: requestURL)
        
        backendService.fetchFromBackend(for: Response<[Marka]>.self, request: request, statusCode: 200) { (result) in
            switch result {
            case .failure(let err):
                self.delegate.didHappenError(error: err)
            case .success(let response):
                self.handlePopular(data: response.results)
            }
        }
    }
}


// MARK: - Methods

extension MarksViewModel {
    
    public func selectCell (indexPath: IndexPath) {
        selectedMarka = filteredData[indexPath.section].items[indexPath.row]
    }
    
    private func handleLoadedData (data: Response<[Marka]>, paginate: Bool) {
        let allitems = paginate ? self.filteredData[1].items + data.results : data.results
        
        let container: [Marks] = [Marks(name: "Популярные", items: []), Marks(name: "Все", items: allitems)]
        self.nextURL = data.next
        self.data = container
        self.filteredData = container
        self.delegate.updatePosts()
    }
    
    private func handlePopular (data: [Marka]) {
        if self.data.count >= 2 {
            self.data[0].items = data
        }
        
        if self.filteredData.count >= 2 {
            self.filteredData[0].items = data
        }
        self.delegate.updatePosts()
    }
    
    private func makeRequest (pagination: Bool = false, query: String? = nil) -> URLRequest {
        
        if pagination {
            return URLRequest(url: URL(string: nextURL!)!)
        } else {
            let prmtrs = query == nil ? [] : [URLQueryItem(name: "mark_name", value: query)]
            let urlString = Request(base: carData.saveToGarage ? .garage : .advert, parameters: prmtrs).getUrl(path: "cars/marks")
            
            return URLRequest(url: urlString)
        }
    }
}
